#include "link/include/factory.h"
static char ip[20];//仅在当前文件夹中可见，且保存在全局数据区，方便复用
static char port[10];
extern int server_init(int *sockfd,pfactory_t pfac)
//extern为定义在函数外定义变量的默认修饰符（包括函数），这边加上是为提示之用
{
    int ret;
    bzero(pfac,sizeof(factory_t));
    pfac->conn=mysql_init(NULL);
    sql_init(pfac->conn);
    int fd=open("link/conf/config",O_RDONLY);
    ERROR_CHECK(fd,-1,"open");
    struct stat statbuf;
    fstat(fd,&statbuf);
    char buf[512]={0};
    read(fd,buf,statbuf.st_size+1);
    char threadnum[6]={0};
    char quecapacity[6]={0};
    int i=3,j=0;
    for(j=0;*(buf+i)!='\n';++i,++j)
    {
        *(ip+j)=*(buf+i);
    }
    i+=6;
    for(j=0;*(buf+i)!='\n';++i,++j)
    {
        *(port+j)=*(buf+i);
    }
    i+=11;
    for(j=0;*(buf+i)!='\n';++i,++j)
    {
        *(threadnum+j)=*(buf+i);
    }
    i+=13;
    for(j=0;*(buf+i)!='\n';++i,++j)
    {
        *(quecapacity+j)=*(buf+i);
    }
    i+=10;
    for(j=0;*(buf+i)!='\n';++i,++j)
    {
        *(pfac->homepath+j)=*(buf+i);
    }
    int num=atoi(threadnum);
    int capacity=atoi(quecapacity);
    //初始化线程工厂
    factory_init(pfac,num,capacity);
    //先启动线程池
    factory_start(pfac);
    //再初始化TCP
    ret=tcp_init(sockfd);
    if(-1==ret){printf("tcp_init error happened!\n"); return -1;}
    return 0;
}
extern int tcp_init(int *sockfd)
{
    int ret=0;
    int sfd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sfd,-1,"socket");
    *sockfd=sfd;
    int reuse=1;
    ret=setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(int));
    ERROR_CHECK(ret,-1,"setsockopt");
    struct sockaddr_in ser;
    bzero(&ser,sizeof(ser));
    //ser.sin_family=AF_INET;
    ser.sin_port=htons(atoi(port));
    //ser.sin_addr.s_addr=inet_addr(ip);//No need to set this argument in server part
    ret=bind(sfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
    ERROR_CHECK(ret,-1,"bind");
    listen(sfd,10);
    return 0;
}
